import pkg_resources
import os
import shutil

def parse_load_ep(spec, group=None):
    dist_name, ep = spec.split(":")
    name_group = ep.split("#")
    name = name_group.pop()
    if name_group:
        group = name_group.pop()
    else:
        assert group, ValueError("Group must be specified")
    req = pkg_resources.Requirement.parse(dist_name)
    ep = pkg_resources.load_entry_point(dist_name, group, name)
    return ep.load()

def safe_populate(req, src, dst):
    """
    req - pkg_resource Requirements object
    src - path inside req
    dst - path to create and/or populate
    """
    fh = []
    if isinstance(req, basestring):
        req = pkg_resources.Requirement.parse(req)
        
    if not os.path.exists(dst):
        source = pkg_resources.resource_filename(req, src)
        shutil.copytree(source, dst)
        fh.append(dst)
    else:
        source = pkg_resources.resource_filename(req, src)
        files = pkg_resources.resource_listdir(req, src)
        for fp in files:
            if not fp.startswith('.svn'):
                shutil.copy(os.path.join(source, fp), dst)
                fh.append(dst)
    return fh

def safe_mkdir(path):
    if not os.path.exists(path):
        os.mkdir(path)
        return path
